/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.widget;

import java.util.Calendar;
import java.util.HashMap;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.util.TimetableHelper;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * This is a custom layout widget that is used for showing the weekly header, should be used along with <code>{@link utsc.apps.utschedule.widget.TimeBlockLayout TimeBlockLayout}</code> on the xml. 
 * @author Wenbin
 *
 */
public class TimerWeekHeaderLayout extends LinearLayout implements OnClickListener{

	private int _column=5;
	private static final String[] WEEKDAYS={"MON","TUE","WED","THU","FRI","SAT","SUN"};
	//private LinearLayout[] _headerBtns;
	private static final int[] CALENDAR_WEEK_FIELDS={Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY,Calendar.SATURDAY,Calendar.SUNDAY};
	private int[] _currentWeekDays;
	private boolean _isSundayFirst=false;
	private int _timerulerOffset;
	private int _weekNumber;
	private boolean _update=false;
	private OnDaySelectedListener _onDaySelectedListener;
	private HashMap<Integer,TextView> _dayNums=new HashMap<Integer, TextView>();
	public TimerWeekHeaderLayout(Context context) {
        this(context, null);
    }
	
	public TimerWeekHeaderLayout(Context context, AttributeSet attrs) {
		this(context,attrs,0);
	}
	
	public TimerWeekHeaderLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs);
		
		 final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TimeRulerGridView,
	                defStyle, 0);
		 
		/* _HeaderWidth = a.getDimensionPixelSize(R.styleable.TimeRulerGridView_headerWidth,
	                _HeaderWidth);
	        _HourHeight = a
	                .getDimensionPixelSize(R.styleable.TimeRulerGridView_hourHeight, _HourHeight);
	        _LabelTextSize = a.getDimensionPixelSize(R.styleable.TimeRulerGridView_labelTextSize,
	                _LabelTextSize);
	        _LabelPaddingLeft = a.getDimensionPixelSize(R.styleable.TimeRulerGridView_labelPaddingLeft,
	                _LabelPaddingLeft);
	        _LabelColor = a.getColor(R.styleable.TimeRulerGridView_labelColor, _LabelColor);
	        _DividerColor = a.getColor(R.styleable.TimeRulerGridView_dividerColor, _DividerColor);
	        _StartHour = a.getInt(R.styleable.TimeRulerGridView_startHour, _StartHour);
	        _EndHour = a.getInt(R.styleable.TimeRulerGridView_endHour, _EndHour);*/
		 _column=a.getInt(R.styleable.TimeRulerGridView_column, _column);
		
		//_headerBtns=new LinearLayout[_column];
		
		setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		//setOnClickListener(this);
		setDrawingCacheEnabled(true);
	}
	
	
	
	private void setupHeaderChildren(){
		/*if (childCount>0) {
			for (int i = 0; i < childCount; i++) {
				LinearLayout child=(LinearLayout)getChildAt(i);
				child=setupTimerWeekHeader(child, WEEKDAYS[i], _currentWeekDays[i]);
			}
		}
		else {*/
			for (int i = 0; i < _column; i++) {
				
				LinearLayout child=(LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.week_header, null,false);
				child=setupTimerWeekHeader(i,child,WEEKDAYS[i], _currentWeekDays[i]);
				child.setTag(CALENDAR_WEEK_FIELDS[i]);
				child.setOnClickListener(this);
				/*child.layout(i*width, 0,i*width+ width, 50);*/
				//addViewInLayout(child, -1, getLayoutParams(),false);
				addView(child);
			}
			_update=true;
		//}
	}

	/**
	 * Setup the weekly header 
	 * 
	 * @param weekday
	 * @param day
	 * @return - the inflated lineralayout with the current weekday information
	 */
	private LinearLayout setupTimerWeekHeader(int index,LinearLayout timerWeekHeader,String weekday,int day){
		//if (!_update) {
			TextView weekDayText=(TextView) timerWeekHeader.findViewById(R.id.weekDay);
			weekDayText.setText(weekday);
		//}
		final TextView dayText=(TextView)timerWeekHeader.findViewById(R.id.day);
		dayText.setText(Integer.toString(day));
		_dayNums.put(index, dayText);
		return timerWeekHeader;
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		final int totalWidth=getWidth();
		//Log.d(VIEW_LOG_TAG, "week header layout");
		//setupHeaderChildren();
		//super.onLayout(changed, l, t, r, b);
		final int count = getChildCount();
		final int width=(totalWidth-_timerulerOffset)/_column;
		for (int i = 0; i < count; i++) {
			final View child=getChildAt(i);
			child.layout(_timerulerOffset+1+i*width, 0,_timerulerOffset+1+i*width+ width, child.getMeasuredHeight());
		}
	}
	
	
	public void setHeaderOnClickListener(OnDaySelectedListener listener) {
		this._onDaySelectedListener=listener;
	}

	public int get_weekNumber() {
		return _weekNumber;
	}

	public static interface OnDaySelectedListener{
		public void onDaySelected(int week, int weekday);
	}
	
	public void set_weekNumber(int _weekNumber) {
		this._weekNumber = _weekNumber;
		//use the helper classs to get the current week days
		_currentWeekDays=TimetableHelper.getWeekDays(this._weekNumber,_column, _isSundayFirst);
		//get the offset of the time ruler header 
		
		if (!_update) {
			_timerulerOffset=getResources().getDimensionPixelSize(R.dimen.timeruler_header_width);
			setupHeaderChildren();
		}else {
			int size=_currentWeekDays.length;
			for (int i = 0; i < size; i++) {
				_dayNums.get(i).setText(Integer.toString(_currentWeekDays[i]));
			}
		}
		
		//invalidate();
	}

	@Override
	public void onClick(View v) {
		if (_onDaySelectedListener!=null) {
			int weekday=(Integer) v.getTag();
			_onDaySelectedListener.onDaySelected(_weekNumber, weekday);
		}
	}

}
